package ch.fhnw.qualiscan.application.views;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.controllers.EditSurvey;
import ch.fhnw.qualiscan.application.modals.AddParticipantToSurvey;
import ch.fhnw.qualiscan.application.modals.DeleteParticipantFromSurvey;
import ch.fhnw.qualiscan.application.modals.DeleteSurvey;
import ch.fhnw.qualiscan.application.modals.DomainHelper;
import ch.fhnw.qualiscan.application.modals.NextStageModal;
import ch.fhnw.qualiscan.core.View;
import ch.fhnw.qualiscan.core.db.fieldfactories.SurveyFieldFactory;
import ch.fhnw.qualiscan.core.db.helpers.participantsTableArgs;
import ch.fhnw.qualiscan.core.db.pojos.Domain;
import ch.fhnw.qualiscan.core.db.pojos.DomainText;
import ch.fhnw.qualiscan.core.db.pojos.Language;
import ch.fhnw.qualiscan.core.db.pojos.Question;
import ch.fhnw.qualiscan.core.db.pojos.Role;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.helpers.EmailHelper;
import ch.fhnw.qualiscan.core.libraries.NotificationLibrary;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.ProgressIndicator;
import com.vaadin.ui.TabSheet.Tab;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.BaseTheme;
import eu.livotov.tpt.TPTApplication;
import eu.livotov.tpt.gui.dialogs.OptionDialog;
import eu.livotov.tpt.gui.dialogs.OptionDialog.OptionDialogResultListener;
import eu.livotov.tpt.gui.dialogs.OptionKind;
import eu.livotov.tpt.i18n.TM;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class EditSurveyCoordinatorView extends View {
	
	private VerticalLayout editSurveyWrap;
	private EditSurvey controller;
	
	private Tab tab1;
	private Tab tab2;
	private Tab tab3;
	private Tab tab4;
	
	private VerticalLayout tabLayout1;
	private VerticalLayout tabLayout2;
	private VerticalLayout tabLayout3;
	private VerticalLayout tabLayout4;;
	
	private Panel tab1Panel1;
	private Panel tab1Panel2;
	
	private Panel tab2Panel1;
	private Panel tab2Panel2;
	
	private Panel tab4Panel1;
	private Panel tab4Panel2;
	
	private Table participantsTable = new Table();
	
	public int stage = -1;
	
	public EditSurveyCoordinatorView (EditSurvey controller) {
		this.controller = controller;
	}
	
	@Override
	public void initComponents() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void buildLayout() {
		
		removeAllComponents();
		tabSheet.removeAllComponents();
		
		editSurveyWrap = new VerticalLayout();
		editSurveyWrap.setMargin(false, false, true, false);
		editSurveyWrap.setSpacing(true);
		
		editSurveyWrap.addComponent(textHelper.h1(TM.get("editsurvey.title", controller.getCurrentSurvey().getTitle())));
		
		addComponent(editSurveyWrap);

		tab1 = tabSheet.addTab(buildTab1(), TM.get("editsurvey.tab1.title"), null);
		tab2 = tabSheet.addTab(buildTab2(), TM.get("editsurvey.tab4.title"), null);
		tab3 = tabSheet.addTab(buildTab3(), TM.get("editsurvey.tab2.title"), null);
		tab4 = tabSheet.addTab(buildTab4(), TM.get("editsurvey.tab3.title"), null);
			
		if (controller.getCurrentSurvey().getStage().getId() != Config.STAGE_SURVEY) {
			tab2.setEnabled(false);
			tab3.setEnabled(false);
			tab4.setEnabled(false);
		}
			
		
		editSurveyWrap.addComponent(tabSheet);
		addComponent(editSurveyWrap);
		
		addComponent(tabSheet);
		
	}
	
	public EditSurvey getController() {
		return controller;
	}

	private VerticalLayout buildTab1() {
		tabLayout1 = new VerticalLayout();
		tabLayout1.addComponent(buildTab1Panel1());
		tabLayout1.addComponent(buildTab1Panel2());
		return tabLayout1;
	}
	
	private Panel buildTab1Panel1() {
		tab1Panel1 = new Panel();
		tab1Panel1.addComponent(textHelper.h3(TM.get("editsurvey.tab1.stagepanel.title")));
		
		VerticalLayout spacer = new VerticalLayout();
		spacer.setHeight("15px");
		
		tab1Panel1.addComponent(spacer);
		tab1Panel1.addComponent(stageBox());
	
		return tab1Panel1;
		
	}
	
	private Panel buildTab1Panel2() {
		tab1Panel2 = new Panel();

		tab1Panel2.addComponent(textHelper.h3(TM.get("editsurvey.tab1.progresspanel.title")));
		
		//Progress Panel
		List<SurveyUserRole> surList = controller.surveyModel.getParticipantsOfSurvey(controller.getCurrentSurvey());
		Language l = controller.userSession.getLanguage();	
		Iterator it = controller.getCurrentSurvey().getDomains().iterator();	
		while(it.hasNext()) {
			Domain d = (Domain)it.next();
			DomainText dt = controller.domainModel.getDomainText(d, l);
			
			int totalAnswers = 0;
			for (int i = 0; i < surList.size(); i++) {
				totalAnswers = totalAnswers + controller.domainModel.getNumberOfAnswersForSurAndDomain(surList.get(i), d);
			}
			
			int nQuestions = 0;
			Iterator<Question> questionIterator= d.getQuestions().iterator();
			while (questionIterator.hasNext()) {
				Question q = questionIterator.next();
				if (q.getSubquestions().size() > 0) {
					nQuestions = nQuestions + q.getSubquestions().size();
				}
				else {
					nQuestions++;
				}
			}
			int totalQuestions = nQuestions * surList.size();
			float progress = (float)totalAnswers/(float)totalQuestions;

			// container
			HorizontalLayout container = new HorizontalLayout();
			container.setSpacing(true);
			container.setMargin(true, false, false, false);
			
			//Title
			Label domainTitle = textHelper.span(dt.getText());
			domainTitle.setWidth("300px");
			
			//Indicator
			ProgressIndicator progressIndicator = new ProgressIndicator();
			progressIndicator.setValue(progress);
			progressIndicator.setWidth("");
			progressIndicator.setPollingInterval(180000);
			
			
			container.addComponent(domainTitle);
			container.addComponent(progressIndicator);
			
			container.setComponentAlignment(domainTitle, Alignment.MIDDLE_CENTER);
			container.setComponentAlignment(progressIndicator, Alignment.MIDDLE_CENTER);
			
			tab1Panel2.addComponent(container);
		}
		
		
		
		return tab1Panel2;
	}

	

	private VerticalLayout buildTab2() {
		tabLayout2 = new VerticalLayout();
		
		tabLayout2 = new VerticalLayout();
		
		buildTab2Panel2();
		
		tabLayout2.addComponent(buildTab2Panel1());
		tabLayout2.addComponent(tab2Panel2);
		return tabLayout2;

	}

	private VerticalLayout buildCoordinatorTab3() {
		tabLayout3 = new VerticalLayout();
		return tabLayout3;
	}

	
	private Panel buildTab2Panel1() {
		tab2Panel1 = new Panel();
		
		tab2Panel1.addComponent(textHelper.h2(TM.get("fillout.coordinatorrole.title")));
		tab2Panel1.addComponent(textHelper.span(TM.get("fillout.coordinatorrole.title.desc")));
		
		final ComboBox fillOutRole = new ComboBox();
		List<Role> roleList = controller.roleModel.getParticipantRoles();
		
		for (int i = 0; i < roleList.size(); i++) {
			fillOutRole.addItem(roleList.get(i));
			fillOutRole.setItemCaption(roleList.get(i), controller.userModel.getRoleText(roleList.get(i), controller.userSession.getLanguage()).getTitle());
		}
		
		if (controller.getSurveyUserRole().getFillOutRole() != null) {
			fillOutRole.setValue(controller.getSurveyUserRole().getFillOutRole());
		}
		
		tab2Panel1.addComponent(fillOutRole);
		
		Button saveButton = new Button(TM.get("action.save"));
		saveButton.addListener(new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				//Save fillOutRole
				if (fillOutRole.getValue() != null) {
					controller.getSurveyUserRole().setFillOutRole((Role) fillOutRole.getValue());
					controller.surveyModel.updateSur(controller.getSurveyUserRole());
					NotificationLibrary.showSuccess(TM.get("action.saved"), null);
					tab2Panel2.setEnabled(true);
				}
				else {
					event.getButton().setEnabled(true);
					event.getButton().setCaption(TM.get("fillout.save"));
					NotificationLibrary.showError(TM.get("user.error.role"), "");
					return;
				}
			}
		});
		saveButton.setIcon(Config.ICON_SAVE);
		
		HorizontalLayout saveButtonWrap = new HorizontalLayout();
		saveButtonWrap.setMargin(true, false, false, false);
		
		saveButtonWrap.addComponent(saveButton);
		
		
		tab2Panel1.addComponent(saveButtonWrap);
		
		return tab2Panel1;
	}
	
	private Panel buildTab2Panel2() {
		tab2Panel2 = new Panel();
		tab2Panel2.addComponent(textHelper.h2(TM.get("editsurvey.tab1.ownprogresspanel.title")));
		
		Button domainHelp = new Button(TM.get("helper.domainhelp"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				openModal(new DomainHelper());
			}
		});
		domainHelp.setStyleName(Button.STYLE_LINK);
		
		CssLayout spacer = new CssLayout();
		spacer.setHeight("15px");
		spacer.setWidth("100%");
                CssLayout spacer2 = new CssLayout();
		spacer2.setHeight("15px");
		spacer2.setWidth("100%");
		tab2Panel2.addComponent(spacer);
		tab2Panel2.addComponent(domainHelp);
		tab2Panel2.addComponent(spacer2);
                
		boolean isSurveyFinished = true;
		CssLayout surveyFinishedWrap = new CssLayout();
		surveyFinishedWrap.setVisible(false);
		surveyFinishedWrap.setMargin(true);
		surveyFinishedWrap.setWidth("800px");
		surveyFinishedWrap.setStyleName("box-ok");
		
		Label surveyFinished = new Label();
		surveyFinishedWrap.addComponent(surveyFinished);

		tab2Panel2.addComponent(surveyFinishedWrap);
		
		Language l = controller.userSession.getLanguage();	
		Iterator it = controller.getCurrentSurvey().getDomains().iterator();	
		while(it.hasNext()) {

			Domain d = (Domain)it.next();
			DomainText dt = controller.domainModel.getDomainText(d, l);
			
			int nQuestions = 0;
			Iterator<Question> questionIterator= d.getQuestions().iterator();
			while (questionIterator.hasNext()) {
				Question q = questionIterator.next();
				if (q.getSubquestions().size() > 0) {
					nQuestions = nQuestions + q.getSubquestions().size();
				}
				else {
					nQuestions++;
				}
			}
			
			int totalAnswers = controller.domainModel.getNumberOfAnswersForSurAndDomain(controller.getSurveyUserRole(), d);
			float progress = (float)totalAnswers/(float)nQuestions;
			if (progress != 1.0) {
				isSurveyFinished = false;
			}

			// container
			HorizontalLayout container = new HorizontalLayout();
			container.setSpacing(true);
			container.setMargin(true, false, false, false);
			
			//Title
			Label domainTitle = textHelper.span(dt.getText());
			domainTitle.setWidth("300px");
			
			//Indicator
			ProgressIndicator progressIndicator = new ProgressIndicator();
			progressIndicator.setValue(progress);
			progressIndicator.setWidth("");
			progressIndicator.setPollingInterval(180000);
			
			//Fill in Button
			Button actionButton = new Button(TM.get("editsurvey.fillout"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					Domain domain = (Domain)event.getButton().getData();
					controller.getAppData().getLoaderLib().setUrl("FillOut/0/"+controller.getSurveyUserRole().getId()+"/"+domain.getId()+"/");
				}
			});
			actionButton.setData(d);
			actionButton.setIcon(Config.ICON_EDIT);
			
			if(controller.getCurrentSurvey().getStage().getId() == Config.STAGE_EVALUATION) {
				actionButton.setEnabled(false);
			}
			
			container.addComponent(domainTitle);
			container.addComponent(progressIndicator);
			
			container.addComponent(actionButton);
			container.setComponentAlignment(actionButton, Alignment.MIDDLE_CENTER);
			
			container.setComponentAlignment(domainTitle, Alignment.MIDDLE_CENTER);
			container.setComponentAlignment(progressIndicator, Alignment.MIDDLE_CENTER);

			tab2Panel2.addComponent(container);
		}
		
		if (isSurveyFinished) {
			if(controller.getCurrentSurvey().getStage().getId() == Config.STAGE_SURVEY) {
				surveyFinished.setValue(TM.get("editsurvey.tab1.surveyfinished"));
				surveyFinishedWrap.setVisible(true);
			} else {
				surveyFinished.setValue(TM.get("editsurvey.tab1.surveyfinished.results"));
				surveyFinishedWrap.setVisible(true);
			}
		}
	
		if(controller.getSurveyUserRole().getRole().getId() == Config.COORDINATOR_ID && controller.getSurveyUserRole().getFillOutRole() == null)
			tab2Panel2.setEnabled(false);
		
		return tab2Panel2;
	}
	
	private VerticalLayout buildTab3() {
		tabLayout3 = new VerticalLayout();
		
		controller.getParticipantsTableContainer();
		
		Button newParticipant = new Button(TM.get("action.add"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				openModal(new AddParticipantToSurvey(controller.getCurrentSurvey(), (EditSurveyCoordinatorView) event.getButton().getData()));
			}
		});
		newParticipant.setIcon(Config.ICON_ADDUSER);
		newParticipant.setData(this);
		
		participantsTable = new Table();
		participantsTable.setWidth("100%");
		participantsTable.setPageLength(0);
		participantsTable.setSelectable(false);
		
		participantsTable.addGeneratedColumn("participantProgress", new Table.ColumnGenerator() {
			public Component generateCell(Table source, Object itemId, Object columnId) {
				SurveyUserRole sur = (SurveyUserRole) source.getContainerProperty(itemId, "sur").getValue();
				
				// no progress bar for experts
				if(sur.getRole().getId() == Config.EXPERT_ID) {
					return null;
				}
				
				Iterator<Domain> itd = sur.getSurvey().getDomains().iterator();
				int nQuestions = 0;
				int totalAnswers = 0;
				
				while(itd.hasNext()) {
					Domain d = itd.next();
					Iterator<Question> questionIterator= d.getQuestions().iterator();
					while (questionIterator.hasNext()) {
						Question q = questionIterator.next();
						if (q.getSubquestions().size() > 0) {
							nQuestions = nQuestions + q.getSubquestions().size();
						}
						else {
							nQuestions++;
						}

					}
					totalAnswers = totalAnswers + controller.domainModel.getNumberOfAnswersForSurAndDomain(sur, d);
				}
				
				float progress = (float)totalAnswers/(float)nQuestions;
				ProgressIndicator pi = new ProgressIndicator(progress);
				pi.setPollingInterval(180000);
				
				return pi;
			}
		});
		
		participantsTable.addGeneratedColumn("participantDeleteButton", new Table.ColumnGenerator() {
			public Component generateCell(Table source, Object itemId, Object columnId) {
				Object[] buttonData = new Object[2];
				buttonData[0] = itemId;
				buttonData[1] = source;
 				Button deleteButton = new Button(TM.get("action.delete"), new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						Object[] buttonData = (Object[]) event.getButton().getData();
						participantsTableArgs pta = (participantsTableArgs) buttonData[0];
						Table source = (Table) buttonData[1];
						BeanItemContainer<participantsTableArgs> tableContainer = (BeanItemContainer<participantsTableArgs>) source.getContainerDataSource();
						openModal(new DeleteParticipantFromSurvey(pta, tableContainer));
					}
				});
 				deleteButton.setIcon(Config.ICON_DELETE);
 				deleteButton.setData(buttonData);
				
				return deleteButton;
			}
		});
		
		participantsTable.addGeneratedColumn("participantReminderButton", new Table.ColumnGenerator() {
			public Component generateCell(Table source, final Object itemId, Object columnId) {
				Button reminderButton = new Button(TM.get("action.remind"));
				reminderButton.setData(itemId);
				reminderButton.addListener(new Button.ClickListener() {
					public void buttonClick(final ClickEvent event) {
						final OptionDialog dlg = new OptionDialog (TPTApplication.getCurrentApplication());
						
						// get name or email
						participantsTableArgs object = (participantsTableArgs) itemId;
						String recipient;
						if(object.getFirstname().equals(""))
							recipient = object.getEmail();
						else 
							recipient = object.getFirstname() + " " + object.getLastname();
						
	                    dlg.showConfirmationDialog(TM.get("email.reminder"), TM.get("email.remind", recipient), new OptionDialogResultListener() {
                            public void dialogClosed(OptionKind arg0) {
                                if(arg0 == OptionKind.OK) {
                            		participantsTableArgs pta = (participantsTableArgs) event.getButton().getData();
                            		
                            		EmailHelper eh = new EmailHelper();
                            		EditSurveyCoordinatorView est = (EditSurveyCoordinatorView) event.getButton().getParent().getParent().getParent().getParent().getParent().getParent();
                            		String Coordinator = est.controller.getUserSession().getFirstname() + " " + est.controller.getUserSession().getLastname();
                            		
                            		//User hasn't logged in so far. Send Invitation Mail again.

                            		if(pta.getFirstname().equals("")) {
                            			eh.sendInvitationMail(pta.getSur(), TM.get("email.reminder.invitationtext"));
                            		}
                            		else {
                            			eh.sendEmail(pta.getEmail(), TM.get("email.reminder.subject", est.controller.currentSurvey.getTitle()), TM.get("email.remindertext", pta.getFirstname() + " " + pta.getLastname(), Coordinator, est.controller.currentSurvey.getTitle(), Config.BASE_URL));
                            		}
                            		
                            		
                            		NotificationLibrary.showSuccess(TM.get("action.sent"), TM.get("email.reminder.sent"));
                                }
                            }
	                    });
					}
				});
				reminderButton.setIcon(Config.ICON_USER_COMMENT);
				return reminderButton;
			}
		});
		
		
		participantsTable.setContainerDataSource(controller.tableContainer);
		
		participantsTable.setColumnHeader("firstname", TM.get("editsurvey.participantstable.firstname"));
		participantsTable.setColumnHeader("lastname", TM.get("editsurvey.participantstable.lastname"));
		participantsTable.setColumnHeader("email", TM.get("editsurvey.participantstable.email"));
		participantsTable.setColumnHeader("role", TM.get("editsurvey.participantstable.role"));
		participantsTable.setColumnHeader("participantProgress", TM.get("editsurvey.participantstable.progress"));
		participantsTable.setColumnHeader("participantDeleteButton", TM.get("action.delete"));
		participantsTable.setColumnHeader("participantReminderButton", TM.get("action.remind"));
		
		participantsTable.setVisibleColumns(new Object[]{"firstname", "lastname", "email", "role", "participantProgress", "participantDeleteButton", "participantReminderButton"});
		
		VerticalLayout participantsWrapper = new VerticalLayout();
		participantsWrapper.setSpacing(true);
		participantsWrapper.setMargin(true);
		participantsWrapper.addComponent(textHelper.h3(TM.get("editsurvey.tab2.title")));
		participantsWrapper.addComponent(newParticipant);
		participantsWrapper.addComponent(participantsTable);
		
		tabLayout3.addComponent(participantsWrapper);
		
		
		return tabLayout3;
	}
	
	private VerticalLayout buildTab4() {
		tabLayout4 = new VerticalLayout();
		tabLayout4.addComponent(buildPanel1Tab4());
		tabLayout4.addComponent(buildPanel2Tab4());
		return tabLayout4;
	}
	
	private Panel buildPanel1Tab4() {
		tab4Panel1 = new Panel();
		controller.getSurvey();
		
		Form surveyForm = new Form();
        
		surveyForm.setCaption(TM.get("editsurvey.tab3.title"));
		surveyForm.setDescription(TM.get("editsurvey.tab3.desc"));
		
		
      
        surveyForm.setItemDataSource(controller.surveyItem);
        SurveyFieldFactory sff = new SurveyFieldFactory(controller.survey.getQuestionnaire());
        surveyForm.setFormFieldFactory(sff);
        
        Vector<String> order = new Vector<String>();
        order.add("title");
        order.add("completiondate");
        
        surveyForm.setVisibleItemProperties(order);
        
        HorizontalLayout buttonBar = new HorizontalLayout();
        surveyForm.getFooter().addComponent(buttonBar);
        
        Button saveButton = new Button(TM.get("action.save"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				try {
					Form surveyForm = (Form) event.getButton().getData();
					
					surveyForm.commit();
					controller.surveyModel.updateSurvey(controller.survey);
					controller.rebuildLayout();
					NotificationLibrary.showSuccess(TM.get("action.saved"), null);
					
					// date changed, inform participants
					if(controller.survey.getCompletiondate() != controller.surveyDate) {
						EmailHelper eH = new EmailHelper();
						List<SurveyUserRole> surList = controller.surveyModel.getParticipantsOfSurvey(controller.survey);
						for(SurveyUserRole sur : surList) {
							eH.sendSurveyCompletionDateChanged(sur.getUser(), controller.survey);
						}
					}
				}
				catch (InvalidValueException e) {
                    return;
				}
			}
		});
        saveButton.setIcon(Config.ICON_SAVE);
        saveButton.setData(surveyForm);
        
        HorizontalLayout buttonWrap = new HorizontalLayout();
        buttonWrap.setSpacing(true);
        
        VerticalLayout formWrap = new VerticalLayout();
        formWrap.setSpacing(true);
        
        buttonWrap.addComponent(saveButton);
        
        // if completion date is over
        if(controller.survey.getCompletiondate().compareTo(new Date()) < 0) {
        	HorizontalLayout dateNotice = new HorizontalLayout();
        	dateNotice.setMargin(true);
        	dateNotice.setStyleName("box-warning");
        	dateNotice.addComponent(new Label(TM.get("warning.completiondate")));
        	formWrap.addComponent(dateNotice);
        }
        
        formWrap.addComponent(surveyForm);
        formWrap.addComponent(buttonWrap);
        
        tab4Panel1.addComponent(formWrap);
		
		return tab4Panel1;
	}
	
	private Panel buildPanel2Tab4() {
		tab4Panel2 = new Panel();
		
		VerticalLayout deleteSurveyWrap = new VerticalLayout();
		deleteSurveyWrap.setSpacing(true);
		
		Label deleteSurvey = textHelper.p(TM.get("editsurvey.tab3.p2.delete"));
		
		Button deleteButton = new Button(TM.get("action.delete"));
		deleteButton.addListener(new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				openModal(new DeleteSurvey(controller.getCurrentSurvey()));
			}
		});
		deleteButton.setIcon(Config.ICON_DELETE);
		
		deleteSurveyWrap.addComponent(deleteSurvey);
		deleteSurveyWrap.addComponent(deleteButton);
		
		tab4Panel2.addComponent(deleteSurveyWrap);
		
		
		return tab4Panel2;
	}

	public VerticalLayout stageBox() {
		
		//persist survey
		controller.getCurrentSurvey().getStage();
		String currentStageTitle = controller.surveyModel.getStageText(controller.getCurrentSurvey().getStage(), controller.userSession.getLanguage()).getTitle();
		Label currentStageText = textHelper.p(TM.get("editsurvey.tab1.stagepanel.currentstage", currentStageTitle));
		Label nextStageTextLabel = null;
		
		VerticalLayout stageBox = new VerticalLayout();
		stageBox.setMargin(false, true, true, true);
		stageBox.setSpacing(true);
		stageBox.setStyleName("stageBox");
		stageBox.setWidth("800px");
		
		if (controller.surveyModel.isNextStage(controller.getCurrentSurvey().getStage())) {
			String nextStageText = controller.stageHelper.getNextStageText(controller.getCurrentSurvey().getStage()).getTitle();
			nextStageTextLabel = textHelper.p(TM.get("editsurvey.tab1.stagepanel.nextstage", nextStageText));
		}
		else {
			nextStageTextLabel = new Label(TM.get("editsurvey.tab1.stagepanel.nonextstage"));
		}
		
		Label stageStatus = null;
		Label stageDesc = null;
		Button nextStageButton = null;
		Button evaluationLink = null;
		
		int status = controller.stageHelper.getState(controller.getCurrentSurvey());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		// survey cannot be terminated
		if(status == 1) {
			stageBox.setStyleName("box-warning");
			stageStatus = textHelper.h4(TM.get("state.1.title"));
			stageDesc = textHelper.p(TM.get("state.1.desc", df.format(controller.getCurrentSurvey().getCompletiondate()).toString()));
			nextStageButton = new Button(TM.get("state.1.switch"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					//controller.openModal(new NextStageModal(editSurvey.currentSurvey, (EditSurveyTab1Coordinator) event.getButton().getData(), event));
					controller.loadView();
				}
			});
			nextStageButton.setIcon(Config.ICON_GO_SQUARE);
			stage = 1;
			nextStageButton.setData(this);
			nextStageButton.setEnabled(false);
		}  
		// survey can be terminated
		else if(status == 2) {
			stageBox.setStyleName("box-ok");
			stageStatus = textHelper.h4(TM.get("state.2.title"));
			stageDesc = textHelper.p(TM.get("state.2.desc", df.format(controller.getCurrentSurvey().getCompletiondate()).toString()));
			nextStageButton = new Button(TM.get("state.2.switch"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					openModal(new NextStageModal(controller.getCurrentSurvey(), (EditSurveyCoordinatorView) event.getButton().getData(), event));
				}
			});
			nextStageButton.setIcon(Config.ICON_GO_SQUARE);
			stage = 2;
			nextStageButton.setData(this);
		}
		// survey is terminated
		else if(status == 3) {
			stageBox.setStyleName("box-warning");
			stageStatus = textHelper.h4(TM.get("state.3.title"));
			stageDesc = textHelper.p(TM.get("state.3.desc"));
			
			evaluationLink = new Button(TM.get("goto.evaluation"));
			evaluationLink.setStyleName(BaseTheme.BUTTON_LINK);
			evaluationLink.addListener(new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					controller.getAppData().getLoaderLib().setUrl("Evaluation/0/0/"+ controller.getSurveyUserRole().getId() + "/");
				}
			});

			nextStageButton = new Button(TM.get("state.3.switch"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					openModal(new NextStageModal(controller.getCurrentSurvey(), (EditSurveyCoordinatorView) event.getButton().getData(), event));
				}
			});
			nextStageButton.setIcon(Config.ICON_GO_SQUARE);
			stage = 3;
			nextStageButton.setData(this);
		}
		// survey is closed
		else if(status == 4) {
			stageBox.setStyleName("box-ok");
			stageStatus = textHelper.h4(TM.get("state.4.title"));
			stageDesc = textHelper.p(TM.get("state.4.desc"));
			
			evaluationLink = new Button(TM.get("goto.evaluation"));
			evaluationLink.setStyleName(BaseTheme.BUTTON_LINK);
			evaluationLink.addListener(new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					controller.getAppData().getLoaderLib().setUrl("Evaluation/0/0/"+ controller.getSurveyUserRole().getId() + "/");
				}
			});
		}
		
		stageBox.addComponent(stageStatus);
		stageBox.addComponent(stageDesc);
		
		if(status == 3) {
			stageBox.addComponent(evaluationLink);
			HorizontalLayout buttonWrapper = new HorizontalLayout();
			buttonWrapper.setMargin(true, false, false, false);
			buttonWrapper.addComponent(nextStageButton);
			stageBox.addComponent(buttonWrapper);
		}
		if (status == 4) {
			stageBox.addComponent(evaluationLink);
		}
		
		if(status == 1 || status == 2) {
			stageBox.addComponent(nextStageButton);
		}
		
		return stageBox;
	}

	@Override
	public void reBuild() {
		// TODO Auto-generated method stub
		
	}
	
}
